#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# expects the following variables defined in the environment:
# - BUCKET_CONFIG_NAME: name of env variable with bucket configuration
# - POSTGRESQL_{USER,PASSWORD,HOST,DATABASE}: PostgreSQL

# shellcheck disable=SC1091
. cki_utils.sh

if (( $# < 2 )); then
    echo "Usage: ${0##*/} <group> <rotation>"
    exit 1
fi

# shellcheck disable=SC2154
cki_parse_bucket_spec "${BUCKET_CONFIG_NAME}"
# shellcheck disable=SC2154
AWS_S3=(aws s3 --endpoint "${AWS_ENDPOINT}")
# shellcheck disable=SC2154
S3_PATH="s3://${AWS_BUCKET}/${AWS_BUCKET_PATH}"
BACKUP_GROUP="$1"
BACKUP_ROTATION="$2"

DATA_PATH="/tmp/dump"
mkdir -p "${DATA_PATH}"

cki_echo_yellow "Retrieving lists of previous backups..."
S3_LIST="/tmp/s3-list.txt"
("${AWS_S3[@]}" ls "${S3_PATH}" || true) \
    | awk '{print $NF}' \
    | (grep "${BACKUP_GROUP}.sql.gz$" || true) \
    > "${S3_LIST}"
S3_COUNT="$(wc -l "${S3_LIST}" | awk '{print $1}')"

echo "  ${S3_COUNT} previous backups in group '${BACKUP_GROUP}' found"

cki_echo_yellow "Creating new backup..."
NAME="${S3_PATH}$(date +'%F-%H-%M').${BACKUP_GROUP}.sql.gz"
echo "  Dumping database..."
# shellcheck disable=SC2154
PGPASSWORD="${POSTGRESQL_PASSWORD}" pg_dump --user "${POSTGRESQL_USER}" --host "${POSTGRESQL_HOST}" "${POSTGRESQL_DATABASE}" > "${DATA_PATH}/backup.sql"
echo "  Compressing and uploading dump..."
gzip -c "${DATA_PATH}/backup.sql" | "${AWS_S3[@]}" cp - "${NAME}"
cki_echo_green "  successfully created at ${NAME}"

cki_echo_yellow "Removing previous backups..."
S3_LIST="/tmp/s3-list.txt"
("${AWS_S3[@]}" ls "${S3_PATH}" || true) \
    | awk '{print $NF}' \
    | (grep "${BACKUP_GROUP}.sql.gz$" || true) \
    > "${S3_LIST}"
S3_COUNT="$(wc -l "${S3_LIST}" | awk '{print $1}')"

if (( S3_COUNT > BACKUP_ROTATION )); then
    TO_REMOVE="$(head -n "-${BACKUP_ROTATION}" "${S3_LIST}")"
    # no quotes to get word splitting
    for i in ${TO_REMOVE}; do
        cki_echo_red "  removing ${i}..."
        "${AWS_S3[@]}" rm "${S3_PATH}${i}"
    done
else
    cki_echo_green "  no backups to remove"
fi
